package com.cuit.filter;

import com.cuit.pojo.Doctor;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "d_FirstFilter",
        urlPatterns = {"/doctor_cm/*"})
public class d_FirstFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest requ = (HttpServletRequest)req;
        HttpServletResponse respo = (HttpServletResponse)resp;
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        PrintWriter out = resp.getWriter();
        String requestURI = requ.getRequestURI();		//获得发出请求的客户端URL地址
        String contextPath = requ.getContextPath();		//获取当前应用的根目录
        if (requestURI.contains("/doctor_cm/login/doctor_register.jsp"  )
                ||requestURI.contains("/doctor_cm/personal_data/d_personal.jsp" )) {
            System.out.println("是登录界面");
            chain.doFilter(requ, respo);		//直接放行
        }
        else { //如果不是login页面，则过滤后再放行
            HttpSession session = requ.getSession(true);
            Doctor d=(Doctor)session.getAttribute("doc");
            if (d!=null&&d.getId() != 0&&d.getPassword()!=null&&d.getAge()!=0&&d.getSex()!=null&&d.getGrade()!=null&&
                    d.getDepartment()!=null&&d.getProfile()!=null&&d.getName()!=null||requestURI.contains("/registerr" )
        ||requestURI.contains("/personal" )) {//不为null表示已登录
                System.out.println("医生编辑了");
                chain.doFilter(requ, respo);
            } else {
                out.println("<h2>您没有填完资料，请先填写！2秒后回到编辑资料页面。</h2>"+"<script>alert(/'123/');</script>");
                respo.setHeader("refresh","2;url="+contextPath+"/doctor_cm/personal_data/d_personal.jsp");
                return;//终止过滤
            }

        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
